package com.test.web.jdbc.execute;

import com.test.web.jdbc.JdbcConnection;
import com.test.web.jdbc.exception.JdbcException;
import com.test.web.jdbc.util.SqlUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * com.test.web.jdbc.execute
 *
 * @author 白雨浓
 * date: 2018/10/21 13:11
 * content: 执行 insert update delete
 */
public class ExecuteUpdate {

    private String sql;
    private JdbcConnection jdbcConnection;

    public ExecuteUpdate(String sql, JdbcConnection jdbcConnection) {
        this.sql = sql;
        this.jdbcConnection = jdbcConnection;
    }

    public <T> int exec(T target, Map<String, Object> paramMap) {

        if (paramMap == null) {
            return this.exec(new ArrayList<>());
        }

        SqlUtil.Result result = SqlUtil.convert(this.sql, target, paramMap);
        this.sql = result.getSql();
        return this.exec(result.getParamList());
    }

    public int exec(List<Object> paramList) {
        Connection conn = jdbcConnection.getConnection();
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            if (paramList != null) {
                for (int i = 0; i < paramList.size(); i++) {
                    ps.setObject(i + 1, paramList.get(i));
                }
            }
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new JdbcException("sql run fail: " + e.getMessage());
        }
    }


}
